package com.tianxinweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tianxinweb.entity.BankCard;
import com.tianxinweb.entity.Result;
import com.tianxinweb.enums.ResultEnum;
import com.tianxinweb.exception.MyException;
import com.tianxinweb.service.BankCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cboy
 * @since 2018-08-07
 */
@RestController
@RequestMapping("/bankCard")
public class BankCardController {

    @Autowired
    private BankCardService service;

    /**
     * 添加绑定银行卡
     * @param bankCard
     * @param result
     * @param session
     * @return
     */
    @PostMapping("add")
    public Result add(@RequestBody @Valid BankCard bankCard, BindingResult result, HttpSession session){
        if(result.hasErrors()) throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
        String code = (String) session.getAttribute(bankCard.getPhone());
        if(code==null) throw new MyException(ResultEnum.CHECKCODE_EXPIRED);
        if(!code.equals(bankCard.getCheckcode())) throw new MyException(ResultEnum.CHECKCODE_ERROR);
        Integer userId = (Integer) session.getAttribute("userId");
        bankCard.setUserId(userId);
        service.addBankCard(bankCard);
        return Result.success();
    }

    /**
     * 获取用户银行卡列表
     * @param session
     * @return
     */
    @RequestMapping("getUserBankCard")
    public Result getUserBankCard(HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");
        List<BankCard> list = service.getUserBankCard(userId);
        return Result.success().add("list",list);
    }

    /**
     * 通过id获取详情
     * @param id
     * @param session
     * @return
     */
    @RequestMapping("getDetailById/{id}")
    public Result getDetailById(@PathVariable("id") Integer id, HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");
        BankCard bankCard = service.selectOne(new EntityWrapper<BankCard>()
                .eq("card_id",id)
                .eq("user_id",userId));
        return Result.success().add("detail",bankCard);
    }

    /**
     * 根据id删除信息
     * @param id
     * @return
     */
    @RequestMapping("delete/{id}")
    public Result delete(@PathVariable("id") Integer id){
        service.deleteById(id);
        return Result.success();
    }

}

